package com.heima.kafka;

import org.apache.kafka.clients.producer.*;
import org.junit.Test;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class ProducerQuickStart {

    @Test
    public void sendMsg() throws ExecutionException, InterruptedException {
        //2. 根据idea的提示创建配置类 并完成Kafka的配置
        Properties properties = new Properties();
        //配置服务器的ip和端口
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "42.193.102.62:9092");

        //key和value的序列化的类
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        //设置重试的次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 3);

        //设置消息的压缩方式
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "gzip");

        //1. 创建生产者的核心对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        for (int i=0; i < 10; i++){
            //3. 发送消息
            ProducerRecord<String, String> recod = new ProducerRecord<>("itcast-topic-input",  "hello kafka");
       /*
        同步发送消息
        RecordMetadata recordMetadata = producer.send(recod).get();
        System.out.println(recordMetadata.offset());*/

            //异步发送消息
            producer.send(recod, new Callback() {
                @Override
                public void onCompletion(RecordMetadata metadata, Exception e) {
                    if(null != e){
                        e.printStackTrace();
                    }

                    System.out.println(metadata.offset());
                }
            });
        }


        //4. 关闭生产者
        producer.close();
    }
}
